import React, { Component } from 'react';
import { Modal, Button, Input, Radio, Select, message } from 'antd';
import PropTypes from 'prop-types';
import { addOneday, getAllStrategies, getAllHasPocOnedayList } from '@api/task';
import CheckboxSelect from '@components/checkbox-select';
import cn from 'classnames';
import _ from 'lodash';
import { NAME_RE } from '@util/constants';
import './index.less';
import { connect } from 'react-redux';

const RadioGroup = Radio.Group;
const SelectOptioin = Select.Option;

class OnedayModal extends Component {
  static defaultState = {
    taskName: '',
    taskNameError: '',
    strategyError: '',
    checkedTemplate: '',
    selectedStrategies: [],
    type: 'template',
    isAddingOneday: false
  };
  constructor(props) {
    super(props);
    this.state = {
      ...OnedayModal.defaultState,
      selectedStrategies: [],
      templates: [],
      onedays: []
    };
  }

  componentDidMount() {
    this.loadAllStrategyTemplates();
    this.loadOnedays();
  }

  loadAllStrategyTemplates = () => {
    getAllStrategies().then(res => {
      const templates = _.get(res, 'data.data.list', []);
      this.setState({
        templates
      });
    });
  };

  loadOnedays = () => {
    getAllHasPocOnedayList().then(res => {
      const onedays = _.get(res, 'data.data.list', []);
      this.setState({
        onedays
      });
    });
  };

  onAddTask = () => {
    const {
      taskName,
      type,
      checkedTemplate,
      selectedStrategies,
      taskNameError,
      strategyError,
      templates
    } = this.state;
    if (taskNameError || strategyError) {
      return;
    }
    const { onSuccess } = this.props;
    const body = { name: taskName };
    const error = {};
    if (!taskName) {
      error.taskNameError = '任务名不能为空';
    }

    if (type === 'template' && checkedTemplate) {
      // eslint-disable-next-line
      body.oneday_detail_ids = _.get(
        templates.find(({ _id }) => checkedTemplate === _id),
        'oneday_detail_oids',
        []
      );
    } else if (type === 'custom' && selectedStrategies.length) {
      // eslint-disable-next-line
      body.oneday_detail_ids = selectedStrategies;
    } else {
      error.strategyError = '扫描策略不能为空';
    }

    if (error.taskNameError || error.strategyError) {
      return this.setState(error);
    }
    if (!this.props.modules.includes('detection')) {
      return message.info('演示版本不能下发任务，请联系ZoomEye BE团队获取正式版本');
    }
    this.setState({
      isAddingOneday: true
    });
    addOneday(body)
      .then(() => {
        message.success('下发任务成功');
        this.setState(OnedayModal.defaultState);
        if (typeof onSuccess === 'function') {
          onSuccess();
        }
      })
      .catch(({ type, message: messageString }) => {
        if (type === 'parsed') {
          message.error(messageString);
        } else {
          message.error('下发任务失败');
        }
      })
      .finally(() => {
        this.setState({
          isAddingOneday: false
        });
      });
  };

  onChangeTemplate = checkedTemplate => {
    this.setState({
      checkedTemplate,
      strategyError: ''
    });
  };

  onTypeChange = e => {
    const type = e.target.value;
    this.setState({
      type,
      strategyError: ''
    });
  };

  onCancel = () => {
    this.props.setModalVisible('oneday', false);
    this.setState(OnedayModal.defaultState);
  };

  onChangeTaskName = e => {
    const taskName = e.target.value;
    const body = {
      taskName
    };
    if (!NAME_RE.test(taskName) || taskName.length > 32) {
      body.taskNameError = '任务名格式错误';
    } else {
      body.taskNameError = '';
    }
    this.setState(body);
  };

  onKeyUp = e => {
    if (e.keyCode === 13) {
      this.onAddTask();
    }
  };

  setSelectedStrategies = strategies => {
    this.setState({
      selectedStrategies: strategies,
      strategyError: ''
    });
  };

  render() {
    const { visible, templateIps = [] } = this.props;
    const {
      taskName,
      taskNameError,
      strategyError,
      checkedTemplate,
      type,
      isAddingOneday,
      selectedStrategies,
      templates,
      onedays
    } = this.state;

    const templateSelects = (
      <Select
        value={checkedTemplate}
        onChange={this.onChangeTemplate}
        className="template-selects"
        placeholder="选择策略模板"
      >
        {templates.map(({ name, _id }) => (
          <SelectOptioin key={_id} value={_id}>
            {name}
          </SelectOptioin>
        ))}
      </Select>
    );
    const footer = [
      <Button key="0" onClick={this.onCancel}>
        取消任务
      </Button>,
      <Button type="primary" key="1" onClick={this.onAddTask} loading={isAddingOneday}>
        立即检测
      </Button>
    ];

    return (
      <Modal
        maskClosable={false}
        title="1Day漏洞"
        visible={visible}
        className={cn('tm-oneday-modal', 'no-header-bottom-lines', 'bottom-center', 'padding-24')}
        onCancel={this.onCancel}
        footer={footer}
      >
        <div onKeyUp={this.onKeyUp}>
          <div className="item">
            <div className="left">任务名称</div>
            <div className="right">
              <Input
                placeholder="请输入数字、中文或英文，不超过32个字符"
                value={taskName}
                onChange={this.onChangeTaskName}
              />
              {taskNameError && <p className="error">{taskNameError}</p>}
            </div>
          </div>
          <div className="item">
            <div className="left">探测目标</div>
            <div className="right">
              <p className="goal">
                <div className="goal__desc">所有资产</div>
                <div className="goal__value">
                  {templateIps.map((ip, index) => (
                    <span key={index}>{ip}</span>
                  ))}
                </div>
              </p>
            </div>
          </div>
          <div className="item">
            <div className="left">扫描策略</div>
            <div className="right">
              <div className="select">
                <RadioGroup value={type} onChange={this.onTypeChange}>
                  <Radio value="template">模板</Radio>
                  <Radio value="custom">自定义</Radio>
                </RadioGroup>
              </div>

              {type === 'template' ? (
                templateSelects
              ) : (
                <CheckboxSelect
                  className="plugins"
                  placeholder="请输入插件名称进行搜索"
                  options={onedays}
                  selected={selectedStrategies}
                  onChange={this.setSelectedStrategies}
                />
              )}
              {strategyError && <p className="error">{strategyError}</p>}
            </div>
          </div>
        </div>
      </Modal>
    );
  }
}

OnedayModal.propTypes = {
  visible: PropTypes.bool,
  templates: PropTypes.array,
  strategies: PropTypes.array,
  setModalVisible: PropTypes.func,
  onSuccess: PropTypes.func,
  templateIps: PropTypes.array,
  modules: PropTypes.array
};

const mapStateToProps = state => {
  return {
    modules: _.get(state, 'auth.cert.modules', [])
  };
};

export default connect(mapStateToProps)(OnedayModal);
